package org.eae.eldf.framework.security.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import org.eae.eldf.entity.sys.SysOperator;
import org.eae.eldf.framework.utils.MD5;
import org.eae.eldf.service.sys.SysOperatorService;

public class MyUsernamePasswordAuthenticationFilter extends
		UsernamePasswordAuthenticationFilter {

	private Logger logger = LoggerFactory.getLogger(getClass()); 
	@Autowired
	private SysOperatorService operatorService;

	public void setOperatorService(SysOperatorService operatorService) {
		this.operatorService = operatorService;
	}
	
	
    
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
    		HttpServletResponse response) throws AuthenticationException {
    	// TODO Auto-generated method stub
    	
    	if (!request.getMethod().equals("POST")) {  
            throw new AuthenticationServiceException(  
                    "Authentication method not supported: "  
                            + request.getMethod());  
        } 
    	
    	String username = obtainUsername(request);
    	logger.debug("[MyUsernamePasswordAuthenticationFilter] username ==> "+ username);
    	
    	String password = MD5.encode(obtainPassword(request)); 
    	logger.debug("[MyUsernamePasswordAuthenticationFilter] password ==> "+ password);
    	
    	 // 验证用户账号与密码是否对应  
        username = username.trim(); 
        
        SysOperator user = operatorService.queryByUser(username);
        if (user == null || !user.getSpassword().equalsIgnoreCase(password)) {  
            throw new AuthenticationServiceException(  
                    "password or username is notEquals");  
        } 
        
     // UsernamePasswordAuthenticationToken实现 Authentication  
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(  
                username, password.toLowerCase());
        
    	// 允许子类设置详细属性  
        setDetails(request, authRequest);  
        
     // 运行UserDetailsService的loadUserByUsername 再次封装Authentication  
        return this.getAuthenticationManager().authenticate(authRequest); 
    	
    }
}
